package com.fh.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fh.mapper.CategoryMapper;
import com.fh.model.Category;
import com.fh.model.IndexImg;
import com.fh.model.vo.CategoryVO;
import com.fh.service.CategoryService;
import com.fh.utils.ResultState;
import com.fh.vo.ResultVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private ObjectMapper objectMapper=new ObjectMapper();
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public ResultVo queryCategory() {
        List<CategoryVO> categoryVOS =null;
        try {
            //从redis中取出的数据
            String categories = stringRedisTemplate.boundValueOps("categories").get();
            if (categories!=null){
                //从redis中取出的数据返回前台
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, Category.class);
                categoryVOS=objectMapper.readValue(categories,javaType);
            }else {
                //从数据库查询返回前台和放到redis中
                categoryVOS= categoryMapper.queryCategory(0);
                stringRedisTemplate.boundValueOps("categories").set(objectMapper.writeValueAsString(categoryVOS));
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (categoryVOS!=null){
            return new ResultVo(ResultState.OK,"ok",categoryVOS);
        }else {
            return new ResultVo(ResultState.NO,"no",null);
        }

    }

    @Override
    public ResultVo selectCategoryProduct() {
        List<CategoryVO> categoryVOS = categoryMapper.selectCategoryProduct();
        return new ResultVo(ResultState.OK,"ok",categoryVOS);
    }
}
